<?php
//后台按数据库字段搜索类
class Search {
    private $field;
    private $special = array();

    public function __construct($field, $special = array()) {
        $this->field = $field;
        $this->special = $special;        //特殊字段 比如1对应xxx的数据
    }

    public function createForm() {
        $html = '<form method="get" action="__SELF__/act/search">';
        $html .= '<select name="search_field">';
        foreach($this->field as $key=>$value) {
            //显示当前查询字段
            if(isset($_GET['search_field']) && $_GET['search_field'] == $key) {
                $html .= '<option value="'.$key.'" selected="selected">'.$value.'</option>';
            } else {
                $html .= '<option value="'.$key.'">'.$value.'</option>';
            }
        }
        $html .= '</select>';
        //显示当前查询值
        if(isset($_GET['search_value'])) {
            $html .= '<input type="text" name="search_value" class="text" value="'.$_GET['search_value'].'"/>';
        } else {
            $html .= '<input type="text" name="search_value" class="text" />';
        }
        $html .= '<input type="submit" value="查询" class="sub"/>';
        $html .= '</form>';
        return $html;
    }

    public function execute() {
        $searchField = $_GET['search_field'];
        if(count($this->special) == 0) {
            $searchValue = $_GET['search_value'];
            $map[$searchField] = array('like', '%'.$searchValue.'%');
        } else {
            //处理特殊字段，使用数组键值对来通过特定数值识别字段
            foreach($this->special as $key=>$value) {
                if($key == $searchField) {
                    foreach($value as $k=>$v) {
                        if(mb_strpos($k, $_GET['search_value'], 0, 'utf-8') !== false) {
                            $searchValue = $v;
                            $map[$searchField] = array('eq', $searchValue);
                        }
                    }
                } else {
                    $searchValue = $_GET['search_value'];
                    $map[$searchField] = array('like', '%'.$searchValue.'%');
                }
            }
        }
        return $map;
    }
}

?>